<template>
  <div class="backup-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>数据备份与恢复</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showBackupDialog">
              <el-icon><Download /></el-icon>
              创建备份
            </el-button>
            <el-button type="success" @click="showRestoreDialog">
              <el-icon><Upload /></el-icon>
              恢复数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 备份统计 -->
      <div class="backup-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ backupStats.totalBackups }}</div>
                <div class="stat-label">总备份数</div>
              </div>
              <el-icon class="stat-icon" color="#409EFF"><Folder /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ formatSize(backupStats.totalSize) }}</div>
                <div class="stat-label">总大小</div>
              </div>
              <el-icon class="stat-icon" color="#67C23A"><DataBoard /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ backupStats.lastBackup }}</div>
                <div class="stat-label">最后备份</div>
              </div>
              <el-icon class="stat-icon" color="#E6A23C"><Clock /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ backupStats.autoBackup ? '开启' : '关闭' }}</div>
                <div class="stat-label">自动备份</div>
              </div>
              <el-icon class="stat-icon" color="#F56C6C"><Setting /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="备份类型">
            <el-select v-model="searchForm.type" placeholder="请选择备份类型" clearable>
              <el-option label="完整备份" value="full" />
              <el-option label="增量备份" value="incremental" />
              <el-option label="差异备份" value="differential" />
            </el-select>
          </el-form-item>
          <el-form-item label="备份状态">
            <el-select v-model="searchForm.status" placeholder="请选择备份状态" clearable>
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
              <el-option label="进行中" value="running" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 备份列表 -->
      <el-table :data="filteredBackups" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="备份名称" width="200" />
        <el-table-column prop="type" label="备份类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDownload(row)">
              下载
            </el-button>
            <el-button type="success" size="small" @click="handleRestore(row)">
              恢复
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建备份对话框 -->
    <el-dialog
      v-model="backupDialogVisible"
      title="创建备份"
      width="600px"
      @close="handleBackupDialogClose"
    >
      <el-form :model="backupForm" :rules="backupRules" ref="backupFormRef" label-width="120px">
        <el-form-item label="备份名称" prop="name">
          <el-input v-model="backupForm.name" placeholder="请输入备份名称" />
        </el-form-item>
        
        <el-form-item label="备份类型" prop="type">
          <el-select v-model="backupForm.type" placeholder="请选择备份类型" style="width: 100%">
            <el-option label="完整备份" value="full" />
            <el-option label="增量备份" value="incremental" />
            <el-option label="差异备份" value="differential" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备份范围" prop="scope">
          <el-checkbox-group v-model="backupForm.scope">
            <el-checkbox label="users">用户数据</el-checkbox>
            <el-checkbox label="products">商品数据</el-checkbox>
            <el-checkbox label="orders">订单数据</el-checkbox>
            <el-checkbox label="inventory">库存数据</el-checkbox>
            <el-checkbox label="finance">财务数据</el-checkbox>
            <el-checkbox label="system">系统配置</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="压缩方式" prop="compression">
          <el-select v-model="backupForm.compression" placeholder="请选择压缩方式" style="width: 100%">
            <el-option label="无压缩" value="none" />
            <el-option label="GZIP压缩" value="gzip" />
            <el-option label="ZIP压缩" value="zip" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备份描述" prop="description">
          <el-input
            v-model="backupForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备份描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="backupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateBackup" :loading="backupLoading">
          创建备份
        </el-button>
      </template>
    </el-dialog>

    <!-- 恢复数据对话框 -->
    <el-dialog
      v-model="restoreDialogVisible"
      title="恢复数据"
      width="600px"
      @close="handleRestoreDialogClose"
    >
      <el-form :model="restoreForm" :rules="restoreRules" ref="restoreFormRef" label-width="120px">
        <el-form-item label="选择备份文件" prop="backupFile">
          <el-upload
            class="backup-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleBackupFileSuccess"
            :before-upload="beforeBackupFileUpload"
            accept=".sql,.zip,.gz"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择备份文件
            </el-button>
          </el-upload>
          <div v-if="restoreForm.backupFile" class="file-info">
            <el-icon><Document /></el-icon>
            <span>{{ restoreForm.backupFile }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="恢复模式" prop="mode">
          <el-radio-group v-model="restoreForm.mode">
            <el-radio label="full">完全恢复</el-radio>
            <el-radio label="partial">部分恢复</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="restoreForm.mode === 'partial'" label="恢复范围" prop="scope">
          <el-checkbox-group v-model="restoreForm.scope">
            <el-checkbox label="users">用户数据</el-checkbox>
            <el-checkbox label="products">商品数据</el-checkbox>
            <el-checkbox label="orders">订单数据</el-checkbox>
            <el-checkbox label="inventory">库存数据</el-checkbox>
            <el-checkbox label="finance">财务数据</el-checkbox>
            <el-checkbox label="system">系统配置</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="恢复前备份" prop="backupBeforeRestore">
          <el-switch v-model="restoreForm.backupBeforeRestore" />
          <span class="form-tip">恢复前自动创建当前数据备份</span>
        </el-form-item>
        
        <el-form-item label="恢复说明" prop="description">
          <el-input
            v-model="restoreForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入恢复说明"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="restoreDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleRestoreData" :loading="restoreLoading">
          开始恢复
        </el-button>
      </template>
    </el-dialog>

    <!-- 备份进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="备份进度"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="progress-content">
        <el-progress
          :percentage="backupProgress"
          :status="backupProgress === 100 ? 'success' : ''"
          :stroke-width="8"
        />
        <p class="progress-text">{{ backupProgressText }}</p>
        <div v-if="backupProgress === 100" class="progress-actions">
          <el-button type="primary" @click="progressDialogVisible = false">完成</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const backupDialogVisible = ref(false)
const restoreDialogVisible = ref(false)
const progressDialogVisible = ref(false)
const backupLoading = ref(false)
const restoreLoading = ref(false)

// 表单引用
const backupFormRef = ref()
const restoreFormRef = ref()

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  dateRange: []
})

// 备份表单
const backupForm = reactive({
  name: '',
  type: 'full',
  scope: ['users', 'products', 'orders', 'inventory', 'finance', 'system'],
  compression: 'gzip',
  description: ''
})

// 恢复表单
const restoreForm = reactive({
  backupFile: '',
  mode: 'full',
  scope: [],
  backupBeforeRestore: true,
  description: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 备份统计
const backupStats = reactive({
  totalBackups: 0,
  totalSize: 0,
  lastBackup: '无',
  autoBackup: false
})

// 备份进度
const backupProgress = ref(0)
const backupProgressText = ref('准备中...')

// 上传配置
const uploadUrl = '/api/upload'

// 备份列表数据
const backups = ref([
  {
    id: 1,
    name: '完整备份_20240115',
    type: 'full',
    size: 1024000,
    status: 'success',
    createTime: '2024-01-15 10:00:00',
    description: '系统完整备份'
  },
  {
    id: 2,
    name: '增量备份_20240116',
    type: 'incremental',
    size: 256000,
    status: 'success',
    createTime: '2024-01-16 10:00:00',
    description: '增量备份'
  },
  {
    id: 3,
    name: '差异备份_20240117',
    type: 'differential',
    size: 512000,
    status: 'failed',
    createTime: '2024-01-17 10:00:00',
    description: '差异备份失败'
  }
])

// 表单验证规则
const backupRules = {
  name: [
    { required: true, message: '请输入备份名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择备份类型', trigger: 'change' }
  ],
  scope: [
    { required: true, message: '请选择备份范围', trigger: 'change' }
  ]
}

const restoreRules = {
  backupFile: [
    { required: true, message: '请选择备份文件', trigger: 'change' }
  ],
  mode: [
    { required: true, message: '请选择恢复模式', trigger: 'change' }
  ]
}

// 计算属性
const filteredBackups = computed(() => {
  let filtered = backups.value
  
  if (searchForm.type) {
    filtered = filtered.filter(item => item.type === searchForm.type)
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    filtered = filtered.filter(item => {
      const itemDate = item.createTime.split(' ')[0]
      return itemDate >= startDate && itemDate <= endDate
    })
  }
  
  return filtered
})

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = backups.value.length
    backupStats.totalBackups = backups.value.length
    backupStats.totalSize = backups.value.reduce((total, backup) => total + backup.size, 0)
    backupStats.lastBackup = backups.value.length > 0 ? backups.value[0].createTime : '无'
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    type: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showBackupDialog = () => {
  backupDialogVisible.value = true
  resetBackupForm()
}

const showRestoreDialog = () => {
  restoreDialogVisible.value = true
  resetRestoreForm()
}

const handleCreateBackup = async () => {
  if (!backupFormRef.value) return
  
  try {
    await backupFormRef.value.validate()
    backupLoading.value = true
    
    // 模拟创建备份
    progressDialogVisible.value = true
    backupProgress.value = 0
    backupProgressText.value = '准备备份...'
    
    // 模拟备份进度
    const interval = setInterval(() => {
      backupProgress.value += Math.random() * 20
      if (backupProgress.value >= 100) {
        backupProgress.value = 100
        backupProgressText.value = '备份完成'
        clearInterval(interval)
        
        // 添加新备份到列表
        const newBackup = {
          id: Date.now(),
          name: backupForm.name,
          type: backupForm.type,
          size: Math.floor(Math.random() * 1000000) + 100000,
          status: 'success',
          createTime: new Date().toLocaleString(),
          description: backupForm.description
        }
        backups.value.unshift(newBackup)
        
        backupDialogVisible.value = false
        ElMessage.success('备份创建成功')
      } else {
        backupProgressText.value = `备份中... ${Math.floor(backupProgress.value)}%`
      }
    }, 500)
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    backupLoading.value = false
  }
}

const handleRestoreData = async () => {
  if (!restoreFormRef.value) return
  
  try {
    await restoreFormRef.value.validate()
    
    await ElMessageBox.confirm('确定要恢复数据吗？此操作将覆盖当前数据！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    restoreLoading.value = true
    
    // 模拟恢复数据
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    ElMessage.success('数据恢复成功')
    restoreDialogVisible.value = false
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复失败:', error)
      ElMessage.error('数据恢复失败')
    }
  } finally {
    restoreLoading.value = false
  }
}

const handleDownload = (row) => {
  ElMessage.success(`开始下载备份文件：${row.name}`)
  // 这里应该实现实际的文件下载逻辑
}

const handleRestore = (row) => {
  restoreForm.backupFile = row.name
  restoreDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该备份吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = backups.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      backups.value.splice(index, 1)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch {
    // 用户取消删除
  }
}

const handleBackupFileSuccess = (response) => {
  restoreForm.backupFile = response.filename
  ElMessage.success('备份文件上传成功')
}

const beforeBackupFileUpload = (file) => {
  const isValidType = file.type === 'application/sql' || 
                     file.type === 'application/zip' || 
                     file.type === 'application/gzip' ||
                     file.name.endsWith('.sql') ||
                     file.name.endsWith('.zip') ||
                     file.name.endsWith('.gz')
  
  if (!isValidType) {
    ElMessage.error('只能上传 SQL、ZIP 或 GZ 格式的备份文件!')
    return false
  }
  
  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isLt100M) {
    ElMessage.error('备份文件大小不能超过 100MB!')
    return false
  }
  
  return true
}

const handleBackupDialogClose = () => {
  resetBackupForm()
}

const handleRestoreDialogClose = () => {
  resetRestoreForm()
}

const resetBackupForm = () => {
  Object.assign(backupForm, {
    name: '',
    type: 'full',
    scope: ['users', 'products', 'orders', 'inventory', 'finance', 'system'],
    compression: 'gzip',
    description: ''
  })
  backupFormRef.value?.clearValidate()
}

const resetRestoreForm = () => {
  Object.assign(restoreForm, {
    backupFile: '',
    mode: 'full',
    scope: [],
    backupBeforeRestore: true,
    description: ''
  })
  restoreFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 工具方法
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getTypeTagType = (type) => {
  const typeMap = {
    full: 'primary',
    incremental: 'success',
    differential: 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    full: '完整备份',
    incremental: '增量备份',
    differential: '差异备份'
  }
  return textMap[type] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    success: 'success',
    failed: 'danger',
    running: 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    success: '成功',
    failed: '失败',
    running: '进行中'
  }
  return textMap[status] || '未知'
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.backup-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.backup-stats {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  position: relative;
  overflow: hidden;
}

.stat-card .el-card__body {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 32px;
  opacity: 0.3;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.backup-uploader {
  width: 100%;
}

.file-info {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-content {
  text-align: center;
  padding: 20px 0;
}

.progress-text {
  margin-top: 20px;
  color: #606266;
}

.progress-actions {
  margin-top: 20px;
}
</style>
